package com.huel.fragment;

import android.Manifest;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.huel.bean.User;
import com.huel.components.AutoGetCode;
import com.huel.components.TimeCount;
import com.huel.dao.UserDao;
import com.huel.taobaostore.R;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Register_Fragment extends Fragment {
    private static final int MY_PERMISSION_REQUEST_CODE = 10000;
    private UserDao userDao;
    private EditText et_check,username,password;
    private login_Fragment login_fragment;
    private View contextView;
    private TextView checkBtn;
    private TimeCount time;
    private ImageView backBtn;
    private Button btn_reg;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    // 创建view   也可以直接在这里面获取view中的控件。
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        contextView = inflater.inflate(R.layout.fragment_register, container, false);
        init();
        checkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                time.start();
                    //开始计时
            }
        });
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回到登录页面
            }
        });

        btn_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reg(username.getText().toString(),password.getText().toString());
            }
        });



        return contextView;
    }


//    初始化控件
    public void init(){
        //获取控件  获取验证码按钮
        checkBtn =contextView.findViewById(R.id.corner_btn);
        et_check =contextView.findViewById(R.id.et_check);
        backBtn =contextView.findViewById(R.id.backBtn);
        username=contextView.findViewById(R.id.et_username);
        password=contextView.findViewById(R.id.et_password);
        btn_reg=contextView.findViewById(R.id.btn_reg);
        time=new TimeCount(60000,1000,checkBtn);
        //先注册组件 再申请权限
        checkPermission();
        userDao= new UserDao(getActivity());
    }
        // 自动得到验证码
    public void getCode(){
        AutoGetCode autoGetCode = new AutoGetCode(getActivity(), new Handler(),
                et_check);//regist_code 要显示验证码的EditText
        // 注册短信变化监听
        getActivity().getContentResolver().registerContentObserver(
                Uri.parse("content://sms/"), true, autoGetCode);
    }


    public void getLogin() {
        if (login_fragment == null ) {
            login_fragment = new login_Fragment();
        }
        login_fragment.setUsername(username.getText().toString());

        //创建FragmentManager对象
        FragmentManager manager = getFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment, login_fragment);
        //提交事务
        fragmentTransaction.commit();
    }


    //显示提示信息
    public void toast(String content){
        Toast.makeText(getActivity(),content,Toast.LENGTH_SHORT).show();
    }
    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                toast("检查权限");
                return false;
            }
        }
        return true;
    }
    public void checkPermission() {
        /**
         * 第 1 步: 检查是否有相应的权限
         */
        boolean isAllGranted = checkPermissionAllGranted(
                new String[] {
                        Manifest.permission.SEND_SMS,
                        Manifest.permission.READ_SMS,
                        Manifest.permission.RECEIVE_SMS,
//                        Manifest.permission.CAMERA
                }
        );
        // 如果这3个权限全都拥有, 则直接执行读取短信代码
        if (isAllGranted) {
             getCode();
            toast("所有权限已经授权！");
            return;
        }
    }


    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                // 如果所有的权限都授予了, 则执行读取短信代码
               getCode();
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
//                openAppDetails();
                toast("需要授权！");
            }
        }
    }

    public void reg(String name,String password) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final  String res = name;
        Request request = new Request.Builder()
//                在这拼接字符串  GET请求 很不稳健
                .url("http://192.168.199.229:8080/Android_war_exploded/userServlet?action=addUser&username=" +name+
                        "&password=" +password)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败回调
                System.out.println("请检查网络");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String json =response.body().string();//注意response.body().string() 只能调用一次！
                //响应成功,这个回调在子线程中,所以不需要创建线程
                if (response.isSuccessful()) {
                    //isSuccessful方法：如果代码位于（200…300）中，则返回true，这意味着请求已成功接收
                    System.out.println("请求网络Ok");

                    if (json.equals("yes")){
                        //在这写  更新UI操作
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                getLogin();
                                //跳转 fragment
                            }
                        });
                    }


                }





            }
        });
    }




}
